/*
 * @Descripttion:
 * @version:
 * @Author: 淏
 * @Date: 2023-11-23 21:30:19
 * @LastEditors: 淏
 * @LastEditTime: 2024-05-15 15:57:14
 */
import axios from 'axios'
import router from '../router'
import store from '../store/index.js'
import ElementUI from 'element-ui'

import Vue from 'vue'
var vm = new Vue()
//调用方法
const service = axios.create({
  baseURL: 'http://192.168.1.10:28080',
  /* baseURL: 'http://192.168.1.239:28080', */
  /*  baseURL: '/api', */
  timeout: 0,
  //baseURL: '',
  headers: {
    //公共请求头配置，本项目请求头大多数接口是这个，所以这里可以配置一下，对于特殊接口单独配置
    'Content-Type': 'application/x-www-form-urlencoded;',
  },
})

service.interceptors.request.use(
  (config) => {
    if (store.state.token) {
      config.headers.Authorization = 'Bearer ' + store.state.token
    }
    return config
  },
  (error) => {
    console.log(error)
    return Promise.reject()
  }
)

//添加响应拦截器
service.interceptors.response.use(
  function (response) {
    const codes = [
      2001, 2003, 2007, 3002, 3003, 3004, 3006, 3007, 3008, 3009, 3017, 3018,
      3019,
    ]
    // 对响应数据做点什么
    if (response.status < 200 || response.status > 300) {
      vm.$loading.close()
      ElementUI.Notification({
        title: '警告',
        message: '系统' + response.status + '错误，请稍后再试！',
        type: 'warning',
      })
      return response
    } else {
      if (response.data.code === 1) {
        return response.data
      } else if (codes.includes(response.data.code)) {
        vm.$loading.close()
        ElementUI.Notification({
          title: '警告',
          message: response.data.message,
          type: 'warning',
        })
        /*  router.push('/404') */
      } else if (response.data.message) {
        vm.$loading.close()
        ElementUI.Notification({
          title: '警告',
          message: response.data.message,
          type: 'warning',
        })
        return 'error'
      }
    }
    vm.$loading.close()
  },
  function (error) {
    return Promise.reject(error)
  }
)

export default service
